package com.hhj.controller;

import com.hhj.pojo.Role;
import com.hhj.pojo.User;
import com.hhj.service.RoleService;
import com.hhj.service.UserService;
import com.hhj.tools.Constants;
import com.hhj.tools.JsonUtils;
import com.hhj.tools.PageSupport;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @Resource(name = "roleServiceImpl")
    private RoleService roleService;

    @RequestMapping("/login")
    public String login(String userCode, String userPassword, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        User login = userService.login(userCode, userPassword);
        if (login == null) {
            request.setAttribute("error", "账号或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
        request.setAttribute(Constants.USER_SESSION, login);
        request.getSession().setAttribute("userSession", login);
        return "frame";

    }


    @RequestMapping("/toUser")
    public String toUserList(String queryname, Integer queryUserRole, Integer pageIndex, Model model) {
        PageSupport pageSupport = new PageSupport();
        if (pageIndex == null) {
            pageSupport.setCurrentPageNo(1);
        } else {
            pageSupport.setCurrentPageNo(pageIndex);
        }
        if (queryUserRole == null) {
            queryUserRole = 0;
        }
        //设置页数的大小
        pageSupport.setPageSize(Constants.pageSize);
        int userCount = userService.getUserCount(queryname, queryUserRole);
        //设置页码总数
        pageSupport.setTotalCount(userCount);
        //算出当前是分页的index
        int currentPageNo = (pageSupport.getCurrentPageNo() - 1) * pageSupport.getPageSize();
        List<User> userList = userService.getUserList(queryname, queryUserRole, currentPageNo, pageSupport.getPageSize());
        List<Role> roleList = roleService.getRoleList();
        //获取RoleName
        for (int i = 0; i < userList.size(); i++) {
            for (int i1 = 0; i1 < roleList.size(); i1++) {
                if (userList.get(i).getUserRole() == roleList.get(i1).getId()) {
                    userList.get(i).setUserRoleName(roleList.get(i1).getRoleName());
                    break;
                }
            }
        }
        //把值存入model
        if (queryname == null) {
            model.addAttribute("queryUserName", "");
        } else {
            model.addAttribute("queryUserName", queryname);
        }
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("roleList", roleList);
        model.addAttribute("userList", userList);
        model.addAttribute("pages", pageSupport);
        return "userlist";
    }

    @RequestMapping("/add")
    public String addUser(String userCode, String userName, String userPassword, String gender, String birthday, String phone, String address, String userRole, HttpSession session) {

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));

        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        userService.add(user);
        return "redirect:/user/toUser";
    }

    //获取getroleList
    @RequestMapping(value = "/getRoleList")
    @ResponseBody//不经过视图解析器
    public String getRoleList() {
        List<Role> roleList = roleService.getRoleList();
        String s = JsonUtils.getJson(roleList);
        return s;
    }


    @RequestMapping(value = "/ucexist")
    @ResponseBody
    public String userExist(String userCode) {

        HashMap<String, String> map = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            map.put("userCode", "exist");
        } else {
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                map.put("userCode", "exist");
            } else {
                map.put("userCode", "notexist");
            }
        }
        return JsonUtils.getJson(map);

    }

    //通过id获取user跳转至userview.jsp
    @RequestMapping("/touserview")
    public String toUserView(String uid, Model model) {
        User userById = userService.getUserById(uid);
        List<Role> roleList = roleService.getRoleList();
        for (int i = 0; i < roleList.size(); i++) {
            if (userById.getId() == roleList.get(i).getId()) {
                userById.setUserRoleName(roleList.get(i).getRoleName());
                break;
            }
        }

        model.addAttribute("user", userById);
        return "userview";
    }

    @RequestMapping("/tousermodify")
    public String toUserModify(String uid, Model model) throws ParseException {
        User userById = userService.getUserById(uid);
        List<Role> roleList = roleService.getRoleList();
        for (int i = 0; i < roleList.size(); i++) {
            if (userById.getId() == roleList.get(i).getId()) {
                userById.setUserRoleName(roleList.get(i).getRoleName());
                break;
            }
        }
        model.addAttribute("user", userById);
        return "usermodify";
    }

    @RequestMapping("/updateUser")
    public String updateUser(String uid, String userName, String userPassword, String gender, String birthday, String phone, String address, String userRole, HttpSession session) {

        User user = new User();
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setId(Integer.parseInt(uid));
        user.setPhone(phone);
        user.setUserRole(Integer.parseInt(userRole));
        user.setAddress(address);
        user.setCreationDate(new Date());
        user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)).getId());
        userService.modify(user);
        return "redirect:/user/toUser";
    }

    @ResponseBody
    @RequestMapping("/delUser")
    public String delUser(String uid) {
        Integer delId = Integer.parseInt(uid);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            if (userService.deleteUserById(delId)) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }
        return JsonUtils.getJson(resultMap);
    }

    @RequestMapping("/pwdmodify")
    @ResponseBody
    public String pwdmodify(String oldpassword, HttpSession session){
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        HashMap map = new HashMap();
        if (user == null) {
            map.put("result", "sessionerror");
        } else if (user.getUserPassword().equals(oldpassword)) {
            map.put("result", "true");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
            map.put("result", "error");
        } else {
            map.put("result", "false");
        }
        return JsonUtils.getJson(map);
    }


    @RequestMapping("/updatepwd")
    public String updatePwd(String newpassword,Model model,HttpSession session) {
        //获取userid
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        boolean flag = userService.updatePwd(user.getId(), newpassword);
        if(flag){
            model.addAttribute(Constants.SYS_MESSAGE, "修改密码成功,请退出并使用新密码重新登录！");
            session.removeAttribute(Constants.USER_SESSION);//session注销
        }else{
            model.addAttribute(Constants.SYS_MESSAGE, "修改密码失败！");
        }
        return "pwdmodify";

    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);//session注销
        return "redirect:/login.jsp";
    }


}
